<template>
  <view class="phones">
    <view class="phones_top">
      <text>{{ title }}</text>
      <text v-if="curType === 'info'" class="unbind-btn" @click="openConfirm">解绑</text>
    </view>
    <view class="shows" v-if="curType === 'info'">
      <view>手机号</view>
      <view @click="showChangingPad">
        <text>{{ userInfo.mobile }}</text>
        <text></text>
        <uni-icons type="right" color="#999" size="14"></uni-icons>
      </view>
    </view>
    <view class="phones_tel" v-if="curType !== 'info'">
      <text style="font-size: 32rpx">手机号</text>
      <input type="number" placeholder="请输入手机号码" maxlength="11" style="width: 80%" :value="phone"
        @input="onInput($event, 'phone')" />
    </view>
    <view class="phones_tel" v-if="curType !== 'info'">
      <text style="font-size: 32rpx">验证码</text>
      <view class="phones_code">
        <input type="number" placeholder="请输入验证码" maxlength="4" style="width: 50%" :value="code"
          @input="onInput($event, 'code')" />
        <view v-show="canSendcode" class="_code" @click="toSendCode()">验证码</view>
        <view v-show="!canSendcode" class="_code">{{ countdown }}s</view>
      </view>
    </view>
    <ConfirmBtns :has-cancel="curType !== 'info'" @cancel="emit('close')" @confirm="confirm" />
  </view>
  <!-- 遮罩样式布局层 -->
  <view v-show="isShowConfirmBox" class="mask-box">
    <view class="inner-mask">
      <Confirm ref="confirmPopup" title="是否解绑手机号码" @cancel="closeConfirm" @confirm="unbind" />
    </view>
  </view>
  <!-- 账户充值到账 -->
  <ReceivedPop ref="received"></ReceivedPop>
</template>

<script setup lang="ts">
  import ReceivedPop from '@c/pobulic/Received.vue';
  import ConfirmBtns from '@c/common/ConfirmBtns.vue';
  import { getDriverID } from '@/stores/driverID';
  import { useUserStore } from '@/stores/user';
  import { errorToast, showLoading, showToast, successToast } from '@/utils/prompt';
  import Confirm from '@c/common/Confirm.vue';
  import { toPublish } from '@mqtt';
  import { computed, nextTick, onBeforeUnmount, ref } from 'vue';
  const props = defineProps({
    type: {
      type: String,
      default: '',
    },
  });
  // static
  const userInfo = useUserStore();
  const driver_id = getDriverID();
  // data
  const curType = computed(() => {
    if (isToChange.value) {
      return 'change';
    } else {
      return props.type;
    }
  });
  const title = computed(() => {
    switch (props.type) {
      case 'bind':
        return '绑定手机号';
      case 'change':
        return '更换手机号码';
      case 'info':
        return '手机号';

      default:
        return '';
    }
  });
  const phone = ref('');
  const code = ref('');
  const countdown = ref(60);
  const isSendingCode = ref(false);
  const canSendcode = ref(true);
  const isShowConfirmBox = ref(false);
  const isToChange = ref(false);
  let intervalID = 0;
  // refs
  const confirmPopup = ref(null);
  const received=ref(null)
  const repeat = ref(true); //放重复点击

  const emit = defineEmits(['close']);

  function showChangingPad() {
    isToChange.value = true;
  }

  function onInput(evt : any, type : string) {
    const { detail } = evt;
    const rule = /[^\d]/g;
    const value = detail.value.replace(rule, '');
    nextTick(() => {
      switch (type) {
        case 'phone':
          phone.value = value;
          break;
        case 'code':
          code.value = value;
          break;
      }
    });
  }

  function validatePhone() {
    const rule = /^1[3-9]\d{9}$/;
    return rule.test(phone.value);
  }

  function toSendCode() {
    if (!isSendingCode.value) {
      if (validatePhone()) {
        sendCode();
      } else {
        showToast('请输入有效的手机号码');
      }
    }
  }
  function startCountdown() {
    canSendcode.value = false;
    countdown.value = 60;
    // @ts-ignore
    intervalID = setInterval(() => {
      countdown.value -= 1;
      if (countdown.value === 0) {
        clearInterval(intervalID);
        canSendcode.value = true;
      }
    }, 1000);
  }
  function sendCode() {
    showLoading();
    isSendingCode.value = true;
    const payload = {
      event: 'notice',
      mobile: phone.value,
    };
    toPublish('driver/sendSms', payload, (obj : any) => {
      isSendingCode.value = false;
      startCountdown();
      successToast('发送成功');
    });
  }

  function openConfirm() {
    isShowConfirmBox.value = true;
    confirmPopup.value.open();
  }
  function closeConfirm() {
    isShowConfirmBox.value = false;
    confirmPopup.value.close();
  }

  function unbind() {
    showLoading('解绑中...');
    if (!repeat.value) {
      return;
    }
    repeat.value = false;
    closeConfirm();
    const payload = {
      driver_id,
      mobile: '',
    };
    toPublish('driver/delDriverMobile', payload, (obj : any) => {
      const { code, msg } = obj;
      if (code === 1) {
        repeat.value = true;
        successToast(msg);
        userInfo.getUserInfo();
        emit('close');
      } else {
        repeat.value = true;
        errorToast(msg);
      }
    });
  }

  function confirm() {
    if (curType.value === 'info') {
      emit('close');
    } else {
      if (!phone.value) {
        showToast('请输入手机号码');
      } else if (!validatePhone()) {
        showToast('请输入正确手机号码');
      } else if (!code.value) {
        showToast('请输入验证码');
      } else {
        updatePhone();
      }
    }
  }

  function updatePhone() {
    showLoading('正在提交');
    const payload = {
      driver_id,
      mobile: phone.value,
      captcha: code.value,
    };
    if (!repeat.value) {
      return;
    }
    repeat.value = false;
    toPublish('driver/editDriverMobile', payload, (obj : any) => {
      const { code, msg } = obj;
      if (code === 1) {
        repeat.value = true;
        successToast(msg);
        userInfo.getUserInfo();
        emit('close');
        setTimeout(()=>{
          received.value.revoke()
        },1000)
      } else {
        repeat.value = true;
        errorToast(msg);
      }
    });
  }

  onBeforeUnmount(() => {
    clearInterval(intervalID);
  });
</script>

<style scoped lang="less">
  @import url('./less/phone_pad.less');

  .box-btn {
    padding: 40rpx 0 20rpx;
  }

  .mask-box {
    position: absolute;
    width: 100%;
    height: 0;
    bottom: 0;

    .inner-mask {
      width: 100%;
      height: 100vh;
      transform: translateY(-100vh);
    }
  }
</style>